package com.ffzl.cloud.ui.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.ffzl.cloud.R;
import com.ffzl.cloud.action.StatusAction;
import com.ffzl.cloud.aop.CheckNet;
import com.ffzl.cloud.aop.DebugLog;
import com.ffzl.cloud.app.AppActivity;
import com.ffzl.cloud.other.IntentKey;
import com.ffzl.cloud.ui.Constants;
import com.ffzl.cloud.ui.dialog.MessageDialog;
import com.ffzl.cloud.utils.EmptyUtil;
import com.ffzl.cloud.utils.XLog;
import com.ffzl.cloud.utils.zxing.BitmapLuminanceSource;
import com.ffzl.cloud.utils.zxing.DecodeFormatManager;
import com.ffzl.cloud.widget.BrowserView;
import com.ffzl.cloud.widget.StatusLayout;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.hjq.bar.TitleBar;
import com.hjq.base.BaseDialog;
import com.hjq.toast.ToastUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2018/10/18
 * desc   : 浏览器界面
 */
public final class BrowserActivity extends AppActivity
        implements StatusAction, OnRefreshListener {

    private static final String TAG = "BrowserActivity";
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private Uri imageUri;
    String picUrl;


    @CheckNet
    @DebugLog
    public static void start(Context context, String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        Intent intent = new Intent(context, BrowserActivity.class);
        intent.putExtra(IntentKey.URL, url);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    private StatusLayout mStatusLayout;
    private ProgressBar mProgressBar;
    //private SmartRefreshLayout mRefreshLayout;
    private BrowserView mBrowserView;
    private TitleBar titlebar;

    MyBrowserChromeClient myBrowserChromeClient;
    MyBrowserViewClient myBrowserViewClient;

    @Override
    protected int getLayoutId() {
        return R.layout.browser_activity;
    }

    @Override
    protected void initView() {
        mStatusLayout = findViewById(R.id.hl_browser_hint);
        mProgressBar = findViewById(R.id.pb_browser_progress);
        // mRefreshLayout = findViewById(R.id.sl_browser_refresh);
        mBrowserView = findViewById(R.id.wv_browser_view);
        titlebar = findViewById(R.id.titlebar);
        //titlebar.setTitle("");
        //titlebar.getRightIcon().setVisible(false,false);
        // titlebar.setVisibility(View.GONE);
        // 设置 WebView 生命管控
        mBrowserView.setLifecycleOwner(this);
        // 设置网页刷新监听
        //mRefreshLayout.setOnRefreshListener(this);

        // 长按保存功能
        mBrowserView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                final WebView.HitTestResult hitTestResult = mBrowserView.getHitTestResult();

                // 如果是图片类型或者是带有图片链接的类型
                if (hitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                        hitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                    picUrl = hitTestResult.getExtra();//获取图片链接
                    XLog.d(picUrl);
                    new MessageDialog.Builder(BrowserActivity.this)
                            .setMessage("提示")
                            .setConfirm("保存图片到本地")
                            .setCancel("跳转到APP")
                            .setCancelable(true)//隐藏
                            .setCanceledOnTouchOutside(true)//隐藏
                            .setListener(new MessageDialog.OnListener() {

                                @Override
                                public void onConfirm(BaseDialog dialog) {
                                    //保存图片到相册
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            url2bitmap(picUrl);
                                        }
                                    }).start();
                                }

                                @Override
                                public void onCancel(BaseDialog dialog) {
                                    if (!EmptyUtil.isEmpty(picUrl)) {
                                        analyzeBitmap(hitTestResult.getExtra(), new AnalyzeCallback() {// 进行图片识别
                                            @Override  //二维码识别
                                            public void onAnalyzeSuccess(Bitmap mBitmap, final String result) {
                                                if (result.toLowerCase().contains("qq")) {
                                                    if (isQQClientAvailable(BrowserActivity.this)) {
                                                        try {
                                                            //加人的  QQ 号码写死
                                                            String url = "mqqwpa://im/chat?chat_type=wpa&uin=1964217030";//uin是发送过去的qq号码
                                                            //添加群的
                                                            //String url = "mqqwpa://im/chat?chat_type=group&uin=670943305&version=1"; //uin是发送过去的qq群号码
                                                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                                                        } catch (Exception e) {
                                                            e.printStackTrace();
                                                        }
                                                    } else {
                                                        ToastUtils.show("当前没有安装QQ");
                                                    }

                                                } else if (result.toLowerCase().contains("wechat")) {
                                                    if (isWeixinAvilible(BrowserActivity.this)) {
                                                        Intent intent = new Intent();
                                                        ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                                                        intent.setAction(Intent.ACTION_MAIN);
                                                        intent.addCategory(Intent.CATEGORY_LAUNCHER);
                                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                        intent.setComponent(cmp);
                                                        startActivity(intent);
                                                    } else {
                                                        ToastUtils.show("当前没有安装微信");
                                                    }
                                                }
                                            }

                                            @Override
                                            public void onAnalyzeFailed() {
                                                ToastUtils.show("无法识别图片，将保存本地~");
                                                new Thread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        url2bitmap(picUrl);
                                                    }
                                                }).start();
                                            }
                                        });


                                    }

                                }
                            })
                            .show();
//                    analyzeBitmap(hitTestResult.getExtra(), new AnalyzeCallback() {
//                        @Override  //二维码识别
//                        public void onAnalyzeSuccess(Bitmap mBitmap, final String result) {
//
//                            // 弹出保存图片的对话框
//                            new MessageDialog.Builder(BrowserActivity.this)
//                                    .setMessage("提示")
//                                    .setConfirm("保存图片到本地")
//                                    .setCancel("跳转到APP")
//                                    .setCancelable(true)//隐藏
//                                    .setCanceledOnTouchOutside(true)//隐藏
//                                    .setListener(new MessageDialog.OnListener() {
//
//                                        @Override
//                                        public void onConfirm(BaseDialog dialog) {
//                                            picUrl = hitTestResult.getExtra();//获取图片链接
//                                            //保存图片到相册
//                                            new Thread(new Runnable() {
//                                                @Override
//                                                public void run() {
//                                                    url2bitmap(picUrl);
//                                                }
//                                            }).start();
//                                        }
//
//                                        @Override
//                                        public void onCancel(BaseDialog dialog) {
//                                            if (result.contains("qq")) {
//                                                if (isQQClientAvailable(BrowserActivity.this)) {
//                                                    try {
//                                                        //加人的  QQ 号码写死
//                                                        String url = "mqqwpa://im/chat?chat_type=wpa&uin=1964217030";//uin是发送过去的qq号码
//                                                        //添加群的
//                                                        //String url = "mqqwpa://im/chat?chat_type=group&uin=670943305&version=1"; //uin是发送过去的qq群号码
//                                                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
//                                                    } catch (Exception e) {
//                                                        e.printStackTrace();
//                                                    }
//                                                } else {
//                                                    ToastUtils.show("当前没有安装QQ");
//                                                }
//
//                                            } else if (result.contains("wechat")) {
//                                                if (isWeixinAvilible(BrowserActivity.this)) {
//                                                    Intent intent = new Intent();
//                                                    ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
//                                                    intent.setAction(Intent.ACTION_MAIN);
//                                                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
//                                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                                                    intent.setComponent(cmp);
//                                                    startActivity(intent);
//                                                } else {
//                                                    ToastUtils.show("当前没有安装微信");
//                                                }
//                                            }
//                                        }
//                                    })
//                                    .show();
//                        }
//
//                        @Override
//                        public void onAnalyzeFailed() {
//                            // 弹出保存图片的对话框
//                            AlertDialog.Builder builder = new AlertDialog.Builder(BrowserActivity.this);
//                            builder.setTitle("提示");
//                            builder.setMessage("保存图片到本地");
//                            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialogInterface, int i) {
//                                    picUrl = hitTestResult.getExtra();//获取图片链接
//                                    //保存图片到相册
//                                    new Thread(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            url2bitmap(picUrl);
//                                        }
//                                    }).start();
//                                }
//                            });
//                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                                // 自动dismiss
//                                @Override
//                                public void onClick(DialogInterface dialogInterface, int i) {
//                                }
//                            });
//                            AlertDialog dialog = builder.create();
//                            dialog.show();
//                        }
//                    });


                    return true;
                }
                return false;//保持长按可以复制文字
            }
        });
    }


    /**
     * 解析二维码图片工具类
     */
    public void analyzeBitmap(final String path, final AnalyzeCallback analyzeCallback) {
        Glide.with(getActivity()).load(path).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                BitmapDrawable bd = (BitmapDrawable) resource;
                Bitmap mBitmap = bd.getBitmap();
                MultiFormatReader multiFormatReader = new MultiFormatReader();

                // 解码的参数
                Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(2);
                // 可以解析的编码类型
                Vector<BarcodeFormat> decodeFormats = new Vector<BarcodeFormat>();
                if (decodeFormats == null || decodeFormats.isEmpty()) {
                    decodeFormats = new Vector<BarcodeFormat>();

                    // 这里设置可扫描的类型，我这里选择了都支持
                    decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
                    decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
                    decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
                }
                hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
                // 设置继续的字符编码格式为UTF8
                // hints.put(DecodeHintType.CHARACTER_SET, "UTF8");
                // 设置解析配置参数
                multiFormatReader.setHints(hints);

                // 开始对图像资源解码
                Result rawResult = null;
                try {
                    rawResult = multiFormatReader.decodeWithState(new BinaryBitmap(new HybridBinarizer(new BitmapLuminanceSource(mBitmap))));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (rawResult != null) {
                    if (analyzeCallback != null) {
                        analyzeCallback.onAnalyzeSuccess(mBitmap, rawResult.getText());
                    }
                    XLog.d(rawResult.getText());
                } else {
                    if (analyzeCallback != null) {
                        analyzeCallback.onAnalyzeFailed();
                    }
                }
            }
        });
    }

    /**
     * 解析二维码结果
     */
    public interface AnalyzeCallback {

        void onAnalyzeSuccess(Bitmap mBitmap, String result);

        void onAnalyzeFailed();
    }


    /**
     * 下载图片
     *
     * @param url
     */
    public void url2bitmap(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;
            int length = http.getContentLength();
            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
            if (bm != null) {
                save2Album(bm);
            }
        } catch (Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(BrowserActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }

    }

    /**
     * 保存到相册
     *
     * @param bitmap
     */
    private void save2Album(Bitmap bitmap) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "相册名称");
        if (!appDir.exists()) appDir.mkdir();
        String[] str = picUrl.split("/");
        String fileName = str[str.length - 1];
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            onSaveSuccess(file);
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(BrowserActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }

    /**
     * 保存成功过
     *
     * @param file
     */
    private void onSaveSuccess(final File file) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                Toast.makeText(BrowserActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    protected void initData() {
        showLoading();

        myBrowserChromeClient = new MyBrowserChromeClient(mBrowserView);
        myBrowserViewClient = new MyBrowserViewClient();
        mBrowserView.setBrowserViewClient(myBrowserViewClient);
        mBrowserView.setBrowserChromeClient(myBrowserChromeClient);
        mBrowserView.loadUrl(getString(IntentKey.URL));
    }

    @Override
    public StatusLayout getStatusLayout() {
        return mStatusLayout;
    }

    @Override
    public void onLeftClick(View view) {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mBrowserView.canGoBack()) {
            // 后退网页并且拦截该事件
            mBrowserView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 重新加载当前页
     */
    @CheckNet
    private void reload() {
        mBrowserView.reload();
    }

    /**
     * {@link OnRefreshListener}
     */
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        // reload();
        //mRefreshLayout.finishRefresh();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        if (resultCode == Constants.SCAN_ACTIVITY_RESULT_CODE) {

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private class MyBrowserViewClient extends BrowserView.BrowserViewClient {

        /**
         * 网页加载错误时回调，这个方法会在 onPageFinished 之前调用
         */
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            // 这里为什么要用延迟呢？因为加载出错之后会先调用 onReceivedError 再调用 onPageFinished
            post(() -> showError(v -> reload()));
        }

        /**
         * 开始加载网页
         */
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            mProgressBar.setVisibility(View.VISIBLE);
        }

        /**
         * 完成加载网页
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            mProgressBar.setVisibility(View.GONE);
            //mRefreshLayout.finishRefresh();
            showComplete();
        }
    }


    private class MyBrowserChromeClient extends BrowserView.BrowserChromeClient {

        private MyBrowserChromeClient(BrowserView view) {
            super(view);
        }

        /**
         * 收到网页标题
         */
        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (title != null) {
                setTitle("");
                setLeftIcon(null);
                setRightIcon(null);
            }
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            if (icon != null) {
                // setRightIcon(new BitmapDrawable(getResources(), icon));
            }
        }

        /**
         * 收到加载进度变化
         */
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            mProgressBar.setProgress(newProgress);
        }
    }


    /**
     * 判断qq是否可用
     *
     * @param context
     * @return
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    //判断微信是否可用
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        // 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);

        // 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }
}
